package logic

import (
	"context"
	"errors"
	"four/sss/weeekrpc/internal/models"
	"gorm.io/gorm"

	"four/sss/weeekrpc/internal/svc"
	"four/sss/weeekrpc/pb/weeekrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Upload todo: 文件入库
func (l *UploadLogic) Upload(in *weeekrpc.UploadRequest) (*weeekrpc.UploadResponse, error) {
	// todo: add your logic here and delete this line
	name := in.FileName
	sux_name := in.SuxName
	userid := in.Userid
	src := in.Src
	size := in.Size
	capacity := in.Capacity
	var r weeekrpc.UploadResponse
	user, _ := models.CreateUser(models.Users{
		Model: gorm.Model{ID: uint(userid)},
	})
	if user.ID == 0 {
		return &r, errors.New("用户不存在")
	}
	user.Capacity = int(capacity)
	_, err := models.SaveUser(user)
	if err != nil {
		return &r, errors.New("保存数据失败")
	}
	//todo: 文件入库失败
	_, err = models.CreateFile(models.Files{
		Userid:   int(userid),
		FileName: name,
		Src:      src,
		SubData:  "表单提交",
		KData:    "无需扩容",
		Name:     "尚鑫平的文件",
		TypeName: sux_name,
		GitSrc:   "shang",
		Size:     int(size),
	})
	return &r, nil
}
